package com.bw.mvvm.mvvm

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.bw.mvvm.model.PostListModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.launch

/**
 * viewModel：调用仓库层数据，通过livedata或者flow流发数据给view层
 */
class PostViewModel:ViewModel(){
    private val mRepository by  lazy {
        PostRepository()
    }
    //方案一；liveData
    //私有 可变MutableLiveData  ：只能在本类访问
    private val mPostLiveData  by lazy {
        MutableLiveData<PostListModel>()
    }
    //公开 不可变LiveData：只能外部访问
    val mPostLiveData_:LiveData<PostListModel> = mPostLiveData


    //方案二：StateFlow：数据加载中 加载成功 失败。。。。
    private val mPostStateFlow by lazy {
        MutableStateFlow<PostState>(PostState.Loading)
    }
    val mPostStateFlow_:StateFlow<PostState> = mPostStateFlow.asStateFlow() //不可变


     // 2：viewModel将请求到的数据放在livedata中
    fun getPostList(pageNum:Int,pageSize:Int){
        viewModelScope.launch{
            mRepository.getPostList(pageNum,pageSize).collect{it->
                mPostLiveData.value = it.data
            }
        }
    }

    fun getPostList2(pageNum:Int,pageSize:Int){
        viewModelScope.launch{
            mRepository.getPostList(pageNum,pageSize)
                .catch{it->
                    mPostStateFlow.value = PostState.Error(it.message.toString())
                }
                .collect{it->
                    if (it.code == 200){
                        if (it.data.size === 0){
                            mPostStateFlow.value = PostState.Empty
                        }else{
                            mPostStateFlow.value = PostState.Success(it.data)
                        }
                    }else{
                        mPostStateFlow.value = PostState.Error(it.message.toString())
                    }

            }
        }
    }


}